﻿using System.Collections.Generic;
using System.Xml.Linq;
using Silent.API.LastFm.Model;

namespace Silent.API.LastFm.Requests
{
    public class AuthnetificationSessionRequest : RequestBase<Session>
    {
        private string ApiKey { get; set; }
        private string Token { get; set; }
        private string Secret { get; set; }
        private bool NeedAuthorization { get; set; }

        public AuthnetificationSessionRequest(string apiKey, string token, string secret, bool needAuthrorization)
            : base(apiKey, QueryConstants.AUTH_GET_SESSION)
        {
            ApiKey = apiKey;
            Token = token;
            Secret = secret;
            NeedAuthorization = needAuthrorization;

            var signatureParameters = new List<string>
                {
                    QueryConstants.PREFIX_API_KEY, apiKey,
                    QueryConstants.PREFIX_METHOD, QueryConstants.AUTH_GET_SESSION,
                    QueryConstants.PREFIX_TOKEN, token,
                    secret
                };

            this.parameters.AddRange(new[]
                {
                    new QueryParameter(QueryConstants.PREFIX_METHOD, QueryConstants.AUTH_GET_SESSION),
                    new QueryParameter(QueryConstants.PREFIX_API_KEY, apiKey),
                    new QueryParameter(QueryConstants.PREFIX_TOKEN, token),
                    new QueryParameter(QueryConstants.PREFIX_API_SIGNATURE, Utility.GetSignature(signatureParameters))
                });
        }

        public override Session Request()
        {
            if (this.NeedAuthorization)
            {
                var authQuery = string.Format("http://www.last.fm/api/auth/?api_key={0}&token={1}", ApiKey, Token);
                System.Diagnostics.Process.Start(authQuery);
            }
            var query = new QueryBuilder().BuildQuery(parameters.ToArray());
            var element = XElement.Load(query).Element("session");
            var objects = Converter.ConvertToSession(element);
            objects.ApiKey = ApiKey;
            objects.Token = Token;
            objects.Secret = Secret;
            return objects;
        }
    }
}